package com.yingli.component.service;

import android.app.DownloadManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.yingli.component.R;
import com.yingli.component.service.utils.NotificationUtils;

public class ServiceActivity extends AppCompatActivity {


    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("serviceStatus", "服务已连接");
            FirstService.MyBinder binder = (FirstService.MyBinder) service;
            String data = binder.getData();
            Log.i("serviceCallback", data);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("serviceStatus", "服务已关闭");
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        findViewById(R.id.btn_bind_service).setOnClickListener(v -> {
            bindService(new Intent(this, FirstService.class), connection, Service.BIND_AUTO_CREATE);
        });
        findViewById(R.id.btn_unbind_service).setOnClickListener(v -> {
            unbindService(connection);
        });
        findViewById(R.id.btn_notification_service).setOnClickListener(v -> {
//            unbindService(connection);
            if (NotificationUtils.isNotificationEnabled(this)) {
                if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
                    startForegroundService(new Intent(this,NotificationService.class));
                }else {
                    startService(new Intent(this, NotificationService.class));
                }
            }else {
                NotificationUtils.gotoSet(this);
            }
        });

        //启动服务
        Intent intent = new Intent(this, FirstService.class);
        findViewById(R.id.btn_start_service).setOnClickListener(v -> {
            intent.putExtra("data", "service start");
            //调用此方法，可以直接下载
//            DownloadManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                startForegroundService(intent);
            } else {
                startService(intent);
            }
        });

        findViewById(R.id.btn_stop_service).setOnClickListener(v -> {
            stopService(intent);
        });
//        unbindService(connection);
//        bindService(new Intent(this,FirstService.class),connection, Service.BIND_AUTO_CREATE);
//        finish();
    }
}
